<template>
  <view class="wish-list-page">
    <!-- 分类标签 -->
    <view class="category-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index" 
        class="tab-item"
        :class="{ active: activeTab === index }"
        @click="activeTab = index"
      >
        {{ tab }}
      </view>
    </view>

    <!-- 愿望列表 -->
    <view class="wish-list">
      <view 
        v-for="wish in filteredWishes" 
        :key="wish.id" 
        class="wish-item"
        @click="viewWishDetail(wish)"
      >
        <view class="wish-content">
          <view class="wish-header">
            <text class="wish-title">{{ wish.title }}</text>
            <view class="wish-category">{{ wish.category }}</view>
          </view>
          <text class="wish-desc">{{ wish.desc }}</text>
          <text class="wish-time">{{ wish.createdAt }}</text>
        </view>
        <view class="wish-actions">
          <button class="edit-btn" @click.stop="editWish(wish)">
            <uni-icons type="compose" size="16" color="#00C853"></uni-icons>
          </button>
          <button class="delete-btn" @click.stop="deleteWish(wish)">
            <uni-icons type="trash" size="16" color="#ff3b30"></uni-icons>
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredWishes.length === 0" class="empty-state">
      <uni-icons type="gift" size="80" color="#ccc"></uni-icons>
      <text class="empty-text">暂无愿望</text>
    </view>

    <!-- 添加愿望按钮 -->
    <view class="add-btn-container">
      <button class="add-btn" @click="showAddForm = true">
        <uni-icons type="plusempty" size="24" color="#fff"></uni-icons>
        <text class="btn-text">添加愿望</text>
      </button>
    </view>

    <!-- 添加/编辑弹窗 -->
    <view v-if="showAddForm" class="modal-overlay" @tap="closePopup">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">{{ editingWish ? '编辑愿望' : '添加愿望' }}</text>
        </view>
        
        <view class="form-item">
          <text class="label">愿望标题</text>
          <input 
            v-model="currentWish.title" 
            placeholder="请输入愿望标题"
            class="input-field"
            :maxlength="50"
          />
        </view>

        <view class="form-item">
          <text class="label">愿望类别</text>
          <picker 
            @change="onCategoryChange" 
            :value="currentWish.categoryIndex" 
            :range="categories"
          >
            <view class="picker-value">
              {{ categories[currentWish.categoryIndex] }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">愿望内容</text>
          <textarea 
            v-model="currentWish.desc" 
            placeholder="请输入愿望的具体描述"
            class="textarea-field"
            :maxlength="200"
          ></textarea>
        </view>

        <view class="form-actions">
          <button class="cancel-btn" @click="closePopup">取消</button>
          <button class="confirm-btn" @click="saveWish">
            {{ editingWish ? '确认修改' : '确定' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { getWishlistByRegion, addWishlist } from '@/api/auth';

const userStore = useUserStore();

// 愿望数据
const wishes = ref<any[]>([]);

// 分类标签
const tabs = ['全部愿望', '美食', '饮品', '甜点', '套餐', '其他'];
const activeTab = ref(0);

// 类别选项
const categories = ['美食', '饮品', '甜点', '套餐', '其他'];

// 当前编辑的愿望
const currentWish = ref({
  title: '',
  desc: '',
  categoryIndex: 0,
  id: null
});

// 弹窗状态
const showAddForm = ref(false);
const editingWish = ref<any>(null);

const customerId = ref(0);
const regionId = ref(1);

// 加载愿望列表
const loadWishlist = async () => {
  if (!userStore.userInfo?.customerId) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({ title: '加载中...' });
    const data: any = await getWishlistByRegion(regionId.value);
    
    if (Array.isArray(data)) {
      wishes.value = data.map((item: any) => ({
        id: item.wishlistId,
        title: item.content || '未命名愿望',
        desc: item.productHint || '',
        category: item.category || '其他',
        createdAt: item.createdAt || ''
      }));
    }
  } catch (error) {
    console.error('获取愿望列表失败:', error);
  } finally {
    uni.hideLoading();
  }
};

// 提交新愿望
const submitWish = async () => {
  if (!currentWish.value.title.trim()) {
    uni.showToast({
      title: '请输入愿望标题',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({ title: '提交中...' });
    
    await addWishlist(
      regionId.value, 
      userStore.userInfo!.customerId, 
      {
        content: currentWish.value.title,
        productHint: currentWish.value.desc
      }
    );
    
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });
    
    closePopup();
    loadWishlist();
  } catch (error) {
    console.error('添加愿望失败:', error);
    uni.showToast({
      title: '添加失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 过滤后的愿望列表
const filteredWishes = computed(() => {
  if (activeTab.value === 0) return wishes.value;
  const category = tabs[activeTab.value];
  return wishes.value.filter(wish => wish.category === category);
});

// 类别选择
const onCategoryChange = (e: any) => {
  currentWish.value.categoryIndex = e.detail.value;
};

// 查看愿望详情
const viewWishDetail = (wish: any) => {
  uni.showToast({
    title: wish.title,
    icon: 'none'
  });
};

// 编辑愿望
const editWish = (wish: any) => {
  currentWish.value = {
    title: wish.title,
    desc: wish.desc,
    categoryIndex: categories.indexOf(wish.category),
    id: wish.id
  };
  editingWish.value = wish;
  showAddForm.value = true;
};

// 删除愿望
const deleteWish = (wish: any) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这个愿望吗?',
    success: (res) => {
      if (res.confirm) {
        const index = wishes.value.findIndex(w => w.id === wish.id);
        if (index !== -1) {
          wishes.value.splice(index, 1);
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 保存愿望
const saveWish = () => {
  if (!currentWish.value.title.trim()) {
    uni.showToast({
      title: '请填写愿望标题',
      icon: 'none'
    });
    return;
  }

  if (editingWish.value) {
    // 更新现有愿望
    const index = wishes.value.findIndex(w => w.id === editingWish.value.id);
    if (index !== -1) {
      wishes.value[index] = {
        ...wishes.value[index],
        title: currentWish.value.title,
        desc: currentWish.value.desc,
        category: categories[currentWish.value.categoryIndex]
      };
      uni.showToast({ title: '修改成功' });
    }
    closePopup();
  } else {
    // 添加新愿望
    submitWish();
  }
};

// 关闭弹窗
const closePopup = () => {
  showAddForm.value = false;
  editingWish.value = null;
  currentWish.value = {
    title: '',
    desc: '',
    categoryIndex: 0,
    id: null
  };
};

// 页面加载
onMounted(() => {
  if (userStore.userInfo?.customerId) {
    customerId.value = userStore.userInfo.customerId;
    regionId.value = userStore.userInfo.regionId || 1;
    loadWishlist();
  }
});
</script>

<style scoped>
.wish-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.category-tabs {
  display: flex;
  overflow-x: auto;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e0e0e0;
  white-space: nowrap;
}

.tab-item {
  padding: 10rpx 25rpx;
  margin-right: 20rpx;
  border-radius: 20rpx;
  background-color: #f5f5f5;
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.tab-item.active {
  background-color: #00C853;
  color: #fff;
}

.wish-list {
  padding: 20rpx;
}

.wish-item {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.wish-content {
  flex: 1;
}

.wish-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.wish-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 15rpx;
}

.wish-category {
  background-color: #e6f7ed;
  color: #00C853;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
}

.wish-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  display: block;
  margin-bottom: 10rpx;
}

.wish-time {
  font-size: 24rpx;
  color: #999;
}

.wish-actions {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-left: 20rpx;
}

.edit-btn, .delete-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  padding: 0;
}

.edit-btn {
  background-color: #e6f7ed;
}

.delete-btn {
  background-color: #fff5f5;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.add-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-btn {
  width: 100%;
  height: 88rpx;
  background-color: #00C853;
  color: #fff;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  font-size: 32rpx;
  border: none;
}

.btn-text {
  font-size: 32rpx;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.modal-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.input-field {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.textarea-field {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 10rpx;
  font-size: 28rpx;
  min-height: 150rpx;
}

.picker-value {
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.cancel-btn {
  flex: 1;
  height: 80rpx;
  background-color: #f0f0f0;
  color: #666;
  border-radius: 10rpx;
  font-size: 28rpx;
  border: none;
}

.confirm-btn {
  flex: 1;
  height: 80rpx;
  background-color: #00C853;
  color: #fff;
  border-radius: 10rpx;
  font-size: 28rpx;
  border: none;
}
</style>